<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #map {
            width: 800px;
            height: 600px;
            background-color: #ccc;
            margin: 50px auto;
            /* 蛇和食物的定位需要依赖地图进行定位 */
            position: relative;
        }
    </style>
    <script src="js/foods.js"></script>
    <script src="js/snakes.js"></script>
</head>

<body>
    <div id="map"></div>

    <script>
        var map = document.querySelector('#map');
        //实例化对象 food
        // var food = new Food();
        // //调用render方法
        // food.render(map);


        // var snake = new Snake();
        // snake.render(map);
        // setInterval(function() {
        //     snake.move(map);
        // }, 100);


        //游戏对象 裁判

        function Game(target) {
            this.food = new Food();
            this.snake = new Snake();
            this.map = target
        }
        Game.prototype.startGame = function() {
            this.food.render(this.map);
            this.snake.render(this.map);
            var that = this;
            var timer = setInterval(function() {
                that.snake.move(that.map, that.food);
                //判断撞墙 
                //因为移动一次就要判断一次 所以写在定时器里面
                var x = that.snake.body[0].x;
                var y = that.snake.body[0].y;
                if (
                    x > that.map.offsetWidth / that.snake.width - 1 ||
                    x < 0 ||
                    y < 0 ||
                    y > that.map.offsetHeight / that.snake.height - 1
                ) {
                    clearInterval(timer);
                    alert('game over!!!!!!');
                }
            }, 100);
            document.addEventListener('keydown', function(e) {
                var e = e.keyCode;
                if (e === 37) {
                    that.snake.direction = 'left';
                } else if (e === 38) {
                    that.snake.direction = 'up';
                } else if (e === 39) {
                    that.snake.direction = 'right';
                } else if (e === 40) {
                    that.snake.direction = 'down';
                }
            });
        };
        var game = new Game(map);
        game.startGame();
        console.log(game);
    </script>
</body>

</html>